#
# @lc app=leetcode.cn id=105 lang=python3
#
# [105] 从前序与中序遍历序列构造二叉树
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        """
        1. 根据前序遍历依次得到根节点
        2. 整个树 = 左子树+右子树
        3. 递归
        """
        # 出口
        if len(inorder) == 0:
            return None

        # 前序遍历的第一个结点就是根节点
        root = TreeNode(preorder[0])
        # 无重复值，找到根节点在中序遍历中的位置
        mid = inorder.index(preorder[0])
        # 构建左子树, 左子树中的根节点：preorder[1:mid + 1]
        root.left = self.buildTree(preorder[1: mid + 1], inorder[:mid])
        # 构建右子树
        root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:])

        return root

# @lc code=end
